package server;

import util.HttpProtocolUtil;
import util.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 封装Response对象，需要依赖于OutputStream
 * 该对象需要提供核⼼方法，输出html
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 根据请求url来获取到静态资源的相对路径, 并进行输出
     * @param staticResourcePath 静态资源请求路径
     * @throws IOException
     */
    public void outputHtml(String staticResourcePath) throws IOException {
        FileInputStream fileInputStream = null;
        try {
            // 输⼊静态资源⽂件
            File file = new File("webapps" + staticResourcePath);
            if(file.exists() && file.isFile()) {
                // 读取静态资源文件，输出静态资源
                fileInputStream = new FileInputStream(file);
                StaticResourceUtil.outputStaticResource(fileInputStream, outputStream);
            }else{
                // 输⼊静态资源文件 默认index.html
                file = new File("webapps" + staticResourcePath + "index.html");
                if(file.exists() && file.isFile()) {
                    // 读取静态资源⽂件，输出静态资源
                    fileInputStream = new FileInputStream(file);
                    StaticResourceUtil.outputStaticResource(fileInputStream, outputStream);
                }else{
                    // 输出404
                    this.output(HttpProtocolUtil.getHttpHeader404());
                }
            }
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * 使用输出流输出指定字符串
     * @param content       要输出的内容
     * @throws IOException
     */
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }
}
